package leetcode.sword;

public class Solution65 {

    public static void main(String[] args) {
        int a = 1, b = -2;
//        System.out.println(Integer.toBinaryString(-1));
//        System.out.println(0b11111111111111111111111111111111);
//        System.out.println(Integer.parseInt("100000000000000000000000",2));
//        System.out.println(Integer.toBinaryString(b));
        System.out.println("final============");
        System.out.println("+:"+(a+b));
        System.out.println("add:"+add(a,b));
    }
    //不用+-*/计算两数之和
    public static int add(int a, int b) {
        boolean full = false;//是否发生进位
        int aLast, bLast; //记录a,b最低二进制位
        int sum = 0;  //记录a,b和的二进制
        System.out.println(""+0+"============");
        System.out.println("a="+Integer.toBinaryString(a));
        System.out.println("b="+Integer.toBinaryString(b));
        System.out.println("sum="+Integer.toBinaryString(sum));
        for (int i = 0; i < 32; i++) {
            //计算二数二进制最后位
            aLast = a&1; bLast = b&1;
            //计算当前位和
            if(aLast==bLast){ //都是0或1
                if(full){
                    sum |= 1;
                }else {
                    sum |= 0; //无进位
                }
                if(aLast==1){
                    full = true;
                }else {
                    full = false;
                }
            }else {  //一个0一个1
                if(full){
                    sum |= 0;
                    full = true;
                }else {
                    sum |= 1; //无进位
                    full = false;
                }
            }
            //a,b无符号右移
            a >>>= 1; b >>>= 1; sum <<= 1;
            System.out.println(""+(i+1)+"============");
            System.out.println("a="+Integer.toBinaryString(a));
            System.out.println("b="+Integer.toBinaryString(b));
            System.out.println("sum="+Integer.toBinaryString(sum));
        }
        return sum;
    }
}
